﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace Common.Net
{
    public class HttpHelper
    {
        public static void Init_Request(ref System.Net.HttpWebRequest request)
        {
            request.Accept = "text/json,*/*;q=0.5";
            request.Headers.Add("Accept-Charset", "utf-8;q=0.7,*;q=0.7");
            request.Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9");
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0";
            request.AutomaticDecompression = System.Net.DecompressionMethods.GZip;
            request.Timeout = 5000;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }

        public static System.Net.HttpWebRequest GetHttpWebRequest(string url)
        {
            HttpWebRequest request = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            return request;
        }
        public static WebResponse Download(string downloadUrl, long from, long to, string method)
        {
            var request = HttpHelper.GetHttpWebRequest(downloadUrl);
            HttpHelper.Init_Request(ref request);
            request.Accept = "text/json,*/*;q=0.5";
            request.AddRange(from, to);
            request.Headers.Add("Accept-Charset", "utf-8;q=0.7,*;q=0.7");
            request.Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9");
            request.AutomaticDecompression = System.Net.DecompressionMethods.GZip;
            request.Timeout = 120000;
            request.Method = method;
            request.KeepAlive = false;
            request.ContentType = "application/json; charset=utf-8";
            return request.GetResponse();
        }
        public static string Get(string url, IDictionary<string, string> param)
        {
            var paramBuilder = new List<string>();
            foreach (var item in param)
            {
                paramBuilder.Add(string.Format("{0}={1}", item.Key, item.Value));
            }
            url = string.Format("{0}?{1}", url.TrimEnd('?'), string.Join(",", paramBuilder.ToArray()));
            return Get(url);
        }

        public static string Get(string url)
        {
            try
            {
                var request = GetHttpWebRequest(url);
                if (request != null)
                {
                    string retval = null;
                    Init_Request(ref request);
                    request.Method = "GET";
                    using (var Response = request.GetResponse())
                    {
                        using (var reader = new System.IO.StreamReader(Response.GetResponseStream(), System.Text.Encoding.UTF8))
                        {
                            retval = reader.ReadToEnd();
                        }
                    }
                    return retval;
                }
            }
            catch
            {

            }
            return null;
        }

        public static string Get(string url, string userAgent = null, string encoding = null, string proxyAddress = null)
        {

            var request = GetHttpWebRequest(url);
            if (request != null)
            {

                string retval = null;
                Init_Request(ref request);
                request.Method = "GET";
                request.ServicePoint.Expect100Continue = false;
                if (userAgent.IsAvailable()) request.UserAgent = userAgent;
                if (proxyAddress.IsAvailable())
                {
                    var addr = proxyAddress.Split(':');
                    var proxy = new WebProxy(addr[0], int.Parse(addr[1]));
                    //var proxy = new WebProxy("27.29.46.63", 9999);
                    //proxy.BypassProxyOnLocal = true;
                    request.Proxy = proxy;
                }
                using (var Response = request.GetResponse())
                {
                    using (var reader = new System.IO.StreamReader(Response.GetResponseStream(), encoding.IsAvailable() ? Encoding.GetEncoding(encoding) : Encoding.UTF8))
                    {
                        retval = reader.ReadToEnd();
                    }
                }
                return retval;
            }
            return "error";

        }
    }
}